package com.dev.security.controller;


import com.dev.security.service.UserService;
import com.dev.security.vo.ResponseData;
import com.dev.security.vo.UserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录
 *
 * @ Author：across-cai
 * @ Time：2020/4/18 14:35
 * @ Motto：我只想做你的太阳
 */
@RestController
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseData login(String username,String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);

        ResponseData responseData = new ResponseData();

        String msg = "";

        //进行登录
        try {
            subject.login(usernamePasswordToken);
            //将用户信息放入session
            UserVo userVo = userService.selectByUsername(username);
            subject.getSession().setAttribute("loginUser",userVo);

            msg = "登录成功";
            responseData.setMessage(msg);
            logger.info("登录成功，username = {}",username);
        }catch (UnknownAccountException e){
            msg = "账号不存在";
            responseData.setMessage(msg);
            responseData.setCode(1);
        }catch (IncorrectCredentialsException e){
            msg = "密码错误";
            responseData.setMessage(msg);
            responseData.setCode(1);
        }catch (Exception e){
            msg = "用户名或密码错误";
            responseData.setMessage(msg);
            responseData.setCode(1);
            e.printStackTrace();
        }


        return responseData;
    }

    @GetMapping("/getLoginUser")
    public ResponseEntity getLoginUser(){
        Subject subject = SecurityUtils.getSubject();
        UserVo userVo = (UserVo) subject.getSession().getAttribute("loginUser");
        return ResponseEntity.ok(userVo);
    }

    @GetMapping("/logout")
    public ResponseEntity logout(){
        Subject subject = SecurityUtils.getSubject();
        //退出登录
        subject.logout();
        return ResponseEntity.ok(0);
    }

}
